import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { TokenResult, UserInfoResult } from '@/types/member'

// 定义 Store
export const useMemberStore = defineStore(
  'member',
  () => {
    // 会员信息
    const profile = ref<TokenResult>()

    // 用户信息
    const userInfo = ref<UserInfoResult>()

    // 保存会员信息，登录时使用
    const setProfile = (val: TokenResult) => {
      profile.value = val
    }

    // 清理会员信息，退出时使用
    const clearProfile = () => {
      profile.value = undefined
    }

    const setUserInfo = (val: UserInfoResult) => {
      userInfo.value = val
    }
    // 清理会员信息，退出时使用
    const clearUserInfo = () => {
      userInfo.value = undefined
    }

    const setCollectCount = (count: number, tag: boolean) => {
      if (tag) {
        if (userInfo.value && userInfo.value.member) {
          userInfo.value.member.collectCount += count
        }
      } else {
        if (userInfo.value && userInfo.value.member) {
          userInfo.value.member.collectCount -= count
        }
      }
    }

    const setCouponCount = (count: number) => {
      if (userInfo.value && userInfo.value.member) {
        userInfo.value.member.couponCount += count
      }
    }
    const getUserInfo = () => userInfo.value as UserInfoResult

    const setSign = (num: number) => {
      if (userInfo.value && userInfo.value.member) {
        userInfo.value.member.signStatus = 1
        userInfo.value.member.points += num
      }
    }

    // 记得 return
    return {
      profile,
      userInfo,
      setSign,
      clearUserInfo,
      getUserInfo,
      setCouponCount,
      setCollectCount,
      setUserInfo,
      setProfile,
      clearProfile,
    }
  },
  // TODO: 持久化
  {
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
